//
//  MANoteManageViewController.m
//  meiang_edu
//
//  Created by 栋 on 2018/12/31.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MANoteManageViewController.h"
#import "MANoteDetailHeader.h"
#import "MANoteDetailViewController.h"
#import "MARightTipView.h"
#import "MAChooseView.h"
#import "MAAlertView.h"
#import "MANoteOneImageCell.h"
#import "MANoteWorkDetailViewController.h"
@interface MANoteManageViewController ()<UITableViewDelegate,UITableViewDataSource,MANoteDetailHeaderProtocol>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/**
 数据源
 */
@property (nonatomic ,strong) NSArray<MANoteManageModel *> * dataSource;

@end

@implementation MANoteManageViewController

#pragma mark - init
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUpNav];
    MAUserInfo * userInfo = [MAUserInfoTool userinfo];
    NSLog(@"userInfo.ID = %@",userInfo.ID);
    [self setUpTableView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self headerRefresh];
}

- (void)setUpTableView{
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"EBEBEB"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 106;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"MANoteOneImageCell" bundle:nil] forCellReuseIdentifier:@"MANoteOneImageCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MANoteDetailHeader" bundle:nil] forCellReuseIdentifier:@"MANoteDetailHeader"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [self.tableView.mj_header beginRefreshing];
}

- (void)setUpNav{
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(tapRightItem) image:@"reminderbutton_logo" highImage:@"Exclamation point"];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)tapRightItem{
    [MARightTipView showWithTips:@"如果您需要删除或停用卡片内容,请长按您所需要操作的卡片"];
}

#pragma mark - 网络请求
- (void)headerRefresh{
    MAUserInfo * userinfo = [MAUserInfoTool userinfo];
    NSString * msgtype = self.funcItemModel.corner_name;
    NSString * entity_type = @"机构";
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?msgtype=%@&entity_type=%@",PICKUP_MSG_LIST,self.jigou_id,msgtype,entity_type];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.dataSource = [MANoteManageModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
            [self.tableView reloadData];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        [self.tableView.mj_header endRefreshing];
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
        
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * cellId = @"MANoteDetailHeader";
    MANoteManageModel * model = self.dataSource[indexPath.row];
    if (model.message_image_count.integerValue == 1) {
        cellId = @"MANoteOneImageCell";
    }
    MANoteDetailHeader * cell =[tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    [cell setCellDataWithModel:model];
    cell.lblType.text = self.funcItemModel.corner_name;
    [cell.imgType ma_setImageWithURL:self.funcItemModel.corner_image placeholderImage:[UIImage new]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.funcItemModel.function_name hasSuffix:@"作业管理"]) {
        MANoteWorkDetailViewController * vc = [MANoteWorkDetailViewController messageDetailViewControllerWith:self.dataSource[indexPath.row]];
        vc.funcItemModel = self.funcItemModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        MANoteDetailViewController * vc = [MANoteDetailViewController messageDetailViewControllerWith:self.dataSource[indexPath.row]];
        vc.funcItemModel = self.funcItemModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

#pragma mark - MANoteDetailHeaderProtocol
//点击cell上的删除
- (void)noteDetailHeaderDidTapDelete:(MANoteDetailHeader *)cell model:(id)model{
    [self deleteMessageWithModel:model];
}
//长按回调
- (void)noteDetailHeaderDidLongPress:(MANoteDetailHeader *)cell model:(MANoteManageModel *)model{
    [MAChooseView showWithDelBlock:^{
        NSLog(@"DelBlock");
        [self deleteMessageWithModel:model];
    } stopBlock:^{
        [self stopUseMessageWithModel:model];
        NSLog(@"stopBlock");
    }];
}
//长按选择删除
- (void)deleteMessageWithModel:(MANoteManageModel *)model{
    [MAAlertView showAlertViewWithMessage:@"您确定删除当前卡片?" MakeSureBlock:^{
        [MANetwork POSTString:CARD_DELETE bodyString:model.keyid autoShowFailAlert:YES showLoading:YES success:^(id response, BOOL success) {
            if (success) {
                [self headerRefresh];
                [MBManager showBriefAlert:@"删除成功"];
            }
        } failure:^(NSError *error) {
            
        }];
    } cancelBlock:^{
        
    }];
}
//长按选择停用
- (void)stopUseMessageWithModel:(MANoteManageModel *)model{
    [MAAlertView showAlertViewWithMessage:@"您确定停用当前卡片?" MakeSureBlock:^{
        [MANetwork GET:[NSString stringWithFormat:@"%@%@",CARD_STOPUSE,model.keyid] parameters:nil autoShowFailAlert:YES showLoading:YES success:^(id response, BOOL success) {
            if (success) {
                [self headerRefresh];
                [MBManager showBriefAlert:@"停用成功"];
            }
        } failure:^(NSError *error) {
            
        }];
    } cancelBlock:^{
        
    }];
}

@end
